const Router = require('koa-router')
const userI = require('../intercepror/user')
const { Book, BookShelf } = require('../db')

const route = new Router({
  prefix: '/bookShelf'
})

route
  .post('/', userI.emailVerified, async ctx => {
    const { bookId } = ctx.request.body
    const book = await Book.findById(bookId)

    const bookShelf = new BookShelf({
      bookId: book._id,
      userId: ctx.user.id,
      bookName: book.name,
      bookAuthor: book.author
    })

    ctx.body = await bookShelf.save()
  })

  .delete('/', userI.emailVerified, async ctx => {
    const { id } = ctx.request.body

    ctx.body = await BookShelf.findByIdAndRemove(id)
  })

  .get('/', userI.emailVerified, async ctx => {
    const { page = 0, pageSize = 20 } = ctx.request.body
    const books = await BookShelf.find({
      userId: ctx.user.id
    })
      .sort({
        createTime: 1
      })
      .skip(parseInt(page) * parseInt(pageSize))
      .limit(parseInt(pageSize))

    ctx.body = books
  })

module.exports = route
